package com.wtwd.device.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.device.model.vo.PageDataVO;
import com.wtwd.device.model.vo.ResultVO;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.model.entity.AppVersion;
import com.wtwd.device.model.vo.AppVersionVo;
import com.wtwd.device.model.vo.RespEntity;
import com.wtwd.device.service.AppVersionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/11/09
 * @description
 */

@Api(tags = "App版本管理")
@RestController
@RequestMapping("/app-version")
public class AppVersionController {

    private static final Logger logger = LoggerFactory.getLogger(AppManagementController.class);


    @Autowired
    private AppVersionService appVersionService;


    /**
     * 分页获取版本控制列表
     *
     * @param currentPage
     * @param pageSize
     * @param appName
     * @return
     */
    @ApiOperation(value = "分页获取版本控制列表", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页面大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "appName", value = "app名称", required = false, dataTypeClass = String.class)
    })
    @GetMapping("/getPageAppVersion")
    public ResultVO<PageDataVO<AppVersionVo>> getPageAppVersion(@RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage
            , @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
            , @RequestParam(value = "appName") String appName) {
        logger.info("getPageAppVersion param  " + currentPage, pageSize, appName);
        if (StringUtils.isBlank(appName)) {
            appName = null;
        }
        Page<Object> page = new Page<>();
        IPage<AppVersionVo> appVersionVos = appVersionService.getPageAppVersionByLikeNameNotInType(appName, 0, page);
        PageDataVO<AppVersionVo> pageDataVO = new PageDataVO<>();
        pageDataVO.setTotal(appVersionVos.getTotal());
        pageDataVO.setRows(appVersionVos.getRecords());
        return ResultVO.success(RespCode.SUCCESS, pageDataVO);
    }


    /**
     * 添加版本
     *
     * @param appVersion
     * @return
     */
    @ApiOperation(value = "添加版本", notes = "")
    @PostMapping("/addAppVersion")
    public RespEntity addAppVersion(@RequestBody AppVersion appVersion) {
        logger.info("addAppVersion param  " + appVersion.toString());
        //校验是否符合添加版本规则
        RespEntity respEntity = checkAddAppVersion(appVersion);
        if (respEntity.getCode() != RespCode.SUCCESS.getCode()) {
            return respEntity;
        }
        appVersion.setCreateTime(new Date().getTime());
        Integer rest = appVersionService.addAppVersion(appVersion);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 编辑版本
     *
     * @param appVersion
     * @return
     */
    @ApiOperation(value = "修改版本", notes = "修改时主键id必传")
    @PutMapping("/updateAppVersion")
    public RespEntity updateAppVersion(@RequestBody AppVersion appVersion) {
        logger.info("updateAppVersion param  " + appVersion.toString());
        RespEntity respEntity = checkUpdateAppVersion(appVersion);
        //参数校验和唯一性校验
        if (respEntity.getCode() != RespCode.SUCCESS.getCode()) {
            return respEntity;
        }
        appVersion.setUpdateTime(new Date().getTime());
        Integer rest = appVersionService.updateAppVersion(appVersion);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * @param appId
     * @param clientType
     * @return
     */
    @ApiOperation(value = "通过appId,客户端类型，获取历史版本", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "appId", value = "appId", required = true, dataType = "Long")
            , @ApiImplicitParam(name = "clientType", value = "客户端类型", required = true, dataType = "int")
    })
    @GetMapping("/getHistoryAppVersion")
    public RespEntity<List<AppVersion>> getHistoryAppVersion(@RequestParam(value = "appId", required = true) Long appId, @RequestParam("clientType") Integer clientType) {
        logger.info("getHistoryAppVersion param  " + appId, clientType);
        if (appId == null || clientType == null) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        AppVersion appVersion = new AppVersion();
        appVersion.setAppId(appId);
        appVersion.setClientType(clientType);
        List<AppVersion> appVersions = appVersionService.getAppVersionByConditions(appVersion);
        return new RespEntity(RespCode.SUCCESS, appVersions);
    }


    /**
     * 校验添加app版本
     * 1.参数校验
     * 2.唯一性校验(appId+clientType+version确定唯一一条数据)
     *
     * @param appVersion
     * @return
     */
    private RespEntity checkAddAppVersion(AppVersion appVersion) {
        if (appVersion.getAppId() == null || appVersion.getClientType() == null
                || StringUtils.isBlank(appVersion.getInstallLocation()) || StringUtils.isBlank(appVersion.getVersion())
                || appVersion.getType() == null || StringUtils.isBlank(appVersion.getDescribe()) ||
                StringUtils.isBlank(appVersion.getLowestVersion())) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        //构建查询条件
        AppVersion searchVersion2 = new AppVersion();
        searchVersion2.setAppId(appVersion.getAppId());
        searchVersion2.setClientType(appVersion.getClientType());
        //此处查询出的数据可能包含多个版本
        List<AppVersion> appVersions = appVersionService.getAppVersionByConditions(searchVersion2);
        //首先查看是否初始化
        if (appVersions == null || appVersions.size() == 0) {
            return new RespEntity(RespCode.APP_VSERSION_NOT_INIT);
        }
        List<AppVersion> appVersionList = appVersions.stream().filter(e -> e.getType().equals(0)).collect(Collectors.toList());
        if (appVersionList == null || appVersionList.size() == 0) {
            return new RespEntity(RespCode.APP_VSERSION_NOT_INIT);
        }
        List<AppVersion> appVersionList2 = appVersions.stream().filter(e -> e.getVersion().equals(appVersion.getVersion())).collect(Collectors.toList());
        if (appVersionList2 != null && appVersionList2.size() > 0) {//如果已经存在该版本
            return new RespEntity(RespCode.APP_VERSION_REPEAT);
        }
        return new RespEntity(RespCode.SUCCESS);
    }


    /**
     * 校验修改app版本
     * 1.参数校验
     * 2.除开自己本身唯一性校验(appId+clientType+version确定唯一一条数据)
     * 3.校验app资源包位置是否发生变化，如果发生则返回发生变化标识符(此处标识符可能为空,成功时不可能为空)
     *
     * @param appVersion
     * @return
     */
    private RespEntity checkUpdateAppVersion(AppVersion appVersion) {//添加时已经校验必须初始化版本(固暂时不修改)
        if (appVersion.getId() == null || appVersion.getAppId() == null || appVersion.getClientType() == null
                || StringUtils.isBlank(appVersion.getInstallLocation()) || StringUtils.isBlank(appVersion.getVersion())
                || appVersion.getType() == null || StringUtils.isBlank(appVersion.getDescribe()) ||
                StringUtils.isBlank(appVersion.getLowestVersion())) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        //构建查询条件
        AppVersion searchVersion = new AppVersion();
        searchVersion.setAppId(appVersion.getAppId());
        searchVersion.setClientType(appVersion.getClientType());
        searchVersion.setVersion(appVersion.getVersion());
        List<AppVersion> appVersions = appVersionService.getAppVersionByConditions(searchVersion);
        if (appVersions != null && appVersions.size() > 0) {
            if (appVersions.size() == 1) {
                AppVersion appVersion1 = appVersions.get(0);
                if (!appVersion1.getId().equals(appVersion.getId())) {//是否是自己本身
                    return new RespEntity(RespCode.APP_VERSION_REPEAT);
                }
            } else {//数据错乱
                return new RespEntity(RespCode.DATA_DISORDER);
            }
        }
        return new RespEntity(RespCode.SUCCESS);
    }
}
